package com.ztgf.sys.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.sys.common.config.YmlConfig;
import com.ztgf.sys.mapper.SysUserRoleRelationMapper;
import com.ztgf.sys.models.bo.SysUserRoleRelationSaveBO;
import com.ztgf.sys.models.constant.SysConstant;
import com.ztgf.sys.models.dto.SysRoleDTO;
import com.ztgf.sys.models.dto.SysUserDTO;
import com.ztgf.sys.models.dto.SysUserRoleRelationDTO;
import com.ztgf.sys.models.service.ISysUserRoleRelationService;
import com.ztgf.sys.models.vo.SysRoleVO;
import com.ztgf.user.models.dto.UserImDTO;
import com.ztgf.user.models.service.IUserImService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户角色关系表  服务实现类
 * </p>
 *
 * @author YUE
 * @since 2020-05-26
 */
@Slf4j
@DubboService
public class SysUserRoleRelationServiceImpl extends ServiceImpl<SysUserRoleRelationMapper, SysUserRoleRelationDTO> implements ISysUserRoleRelationService {
    @Resource
    private YmlConfig ymlConfig;

    @Autowired
    private SysUserRoleRelationMapper sysUserRoleRelationMapper;

    @Autowired
    private SysRoleServiceImpl sysRoleService;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private IUserImService userImService;

    @Override
    public boolean add(SysUserRoleRelationSaveBO saveBO) {
        SysUserRoleRelationDTO dto = new SysUserRoleRelationDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Transactional
    @Override
    public boolean insertOrUpdate(List<String> roleIdList,Long userId) {
        //删除所有与此用户相关联的权限
        deleteByUserId(userId);
        deleteIMByUserId(userId);
        SysUserDTO sysUserDTO = sysUserService.selectById(userId);
        sysUserDTO.setImId(0L);
        sysUserService.updateById(sysUserDTO);
        for (String roleId : roleIdList) {
            if(StrUtils.isEmpty(roleId)){
                continue;
            }
            SysRoleDTO sysRoleDTO = sysRoleService.selectById(roleId);
            //判断有没有客服角色
            if(sysRoleDTO.getName().contains("客服")){
                //创建im记录
                UserImDTO userImDTO = new UserImDTO();
                userImDTO.setType(2);
                userImDTO.setSysUserId(userId);
                Long userImId = ymlConfig.getPkId();
                userImDTO.setId(userImId);
                userImDTO.setConsultationSort(1000);
                userImService.insert(userImDTO);
                sysUserDTO.setImId(userImId);
                sysUserService.updateById(sysUserDTO);
            }

            SysUserRoleRelationDTO sysUserRoleRelationDTO = new SysUserRoleRelationDTO();
            sysUserRoleRelationDTO.setUserId(userId);
            sysUserRoleRelationDTO.setRoleId(Long.parseLong(roleId));
            Long id = ymlConfig.getPkId();
            sysUserRoleRelationDTO.setId(id);
            this.insert(sysUserRoleRelationDTO);
        }
        log.info("update_roleId========================end");
        return true;
    }

    /**
     * 删除相关联的用户角色信息
     * @param userId 用户id
     * @param roleId 角色id
     */
    private void deleteRelationUserRoleInfo(Long userId,Long roleId){
        List<SysRoleDTO> roleListByParentId = sysRoleService.getRoleListByParentId(roleId);//所有的子角色
        for (SysRoleDTO sysRoleDTO : roleListByParentId) {
            deleteRelationUserRoleInfo(userId,sysRoleDTO.getId());
        }
        deleteByUserIdAndRoleId(userId,roleId);
    }

    @Override
    public List<SysRoleDTO> getRoleListByUserId(Long userId) {
        List<SysRoleDTO> sysRoleDTOList = new ArrayList<>();
        Wrapper<SysUserRoleRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId);
        List<SysUserRoleRelationDTO> sysUserRoleRelationDTOList = sysUserRoleRelationMapper.selectList(wrapper);
        for (SysUserRoleRelationDTO sysUserRoleRelationDTO : sysUserRoleRelationDTOList) {
            SysRoleDTO sysRoleDTO = sysRoleService.selectById(sysUserRoleRelationDTO.getRoleId());//用户下所有的角色
            sysRoleDTOList.add(sysRoleDTO);
        }
        return sysRoleDTOList;
    }

    /**
     * 查询出用户下所有角色 树形
     * @param userId
     * @return
     */
    @Override
    public List<SysRoleVO> getRoleIdTreeListByUserId(Long userId){
        List<SysRoleVO> voRoleIdListByUserId = sysUserRoleRelationMapper.getVORoleIdListByUserId(userId);
        return sysRoleService.builTree(voRoleIdListByUserId, SysConstant.ADMIN_ID);
    }


    /**
     * 查询出用户下所有角色
     * @param userId
     * @return
     */
    public List<SysRoleDTO> getRoleIdListByUserId(Long userId){
        return sysUserRoleRelationMapper.getRoleIdListByUserId(userId);
    }

    /**
     * 根据角色id删除关联关系
     * @param roleId 角色id
     */
    public void deleteByRoleId(Long roleId){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("role_id",roleId);
        delete(wrapper);
    }

    /**
     * 根据用户id删除关联关系
     * @param userId 用户id
     */
    public void deleteByUserId(Long userId){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_id",userId);
        delete(wrapper);
    }

    /**
     * 根据用户id删除IM关联关系
     * @param userId 用户id
     */
    public void deleteIMByUserId(Long userId){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("sys_user_id",userId);
        userImService.delete(wrapper);
    }

    /**
     * 根据用户id和角色删除关联关系
     * @param userId 用户id
     */
    public void deleteByUserIdAndRoleId(Long userId,Long roleId){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_id",userId);
        wrapper.eq("role_id",roleId);
        delete(wrapper);
    }

    /**
     * 根据用户id查询关联关系
     * @param userId 用户id
     */
    public List<SysUserRoleRelationDTO> selectListByUserId(Long userId){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_id",userId);
        return selectList(wrapper);
    }

    /**
     * 根据用户id和角色id查询关联关系
     * @param userId 用户id
     * @param roleId 角色id
     */
    public SysUserRoleRelationDTO getByUserIdAndRoleId(Long userId,Long roleId){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_id",userId);
        wrapper.eq("role_id",roleId);
        return selectOne(wrapper);
    }
}